package com.parleys.android.client.io;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.util.Log;

import com.parleys.android.client.provider.ParleysContract;
import com.parleys.android.client.provider.ParleysContract.News;

public class NewsHandler extends JSONHandler {
	
	private static final String TAG = "NewsHandler";
	
	public NewsHandler() {
		super(ParleysContract.CONTENT_AUTHORITY);
	}

	@Override
	public ArrayList<ContentProviderOperation> parse(JSONArray json, ContentResolver resolver) throws JSONException {
		ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
		
		final int jsonSize = json.length();
		for (int i = 0; i < jsonSize; i++) {
			final JSONObject news = json.getJSONObject(i);
			final long newsId = news.getLong("id");
			final long createdOn = news.getLong("createdOn");
			final long modifiedOn = news.getLong("modifiedOn");
			final String title = news.getString("title");
			final String item = news.getString("item");
			final String author = news.getString("author");
			
			batch.add(ContentProviderOperation.newInsert(News.CONTENT_URI)
				.withValue(News.NEWS_ID, newsId)
				.withValue(News.CREATED_ON, createdOn)
				.withValue(News.MODIFIED_ON, modifiedOn)
				.withValue(News.TITLE, title)
				.withValue(News.ITEM, item)
				.withValue(News.AUTHOR, author)
				.withValue(News.READ, false)
				.build());
		}
		
		return batch;
	}

	@Override
	public void notify(ContentProviderResult[] result, ContentResolver resolver) throws JSONException {
		if (result != null && result.length > 0) {
			Log.d(TAG, "Notifying data set changes for " + News.CONTENT_URI);
			resolver.notifyChange(News.CONTENT_URI, null);
		}
	}

}
